<?php


namespace App\Http\Controllers;


use App\Facade\System\File;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class FileController extends Controller
{
    function image($id, $w = 0, $h = 0)
    {
        $url = File::defaultImage();
        if ($id) {
            $file = \App\Models\System\File::find($id);
            if ($file) {
                if ($file->type == 1) {
                    if ($w && $h) {
                        $path = substr_replace($file->path, $w . '_' . $h, strrpos($file->path, '.'), 0);
                        if (!Storage::exists($path)) {
                            Image::make(Storage::path($file->path))->resize($w, $h)->save(Storage::path($path));
                        }
                        $url = Storage::url($path);
                    } else {
                        $url = Storage::url($file->path);
                    }
                } else {
                    $params = '';
                    if ($w && $h) {
                        $params = "?x-oss-process=image/resize,m_fill,h_$w,w_$h";
                    }

                    $url = 'https://' . config('ali_oss.bucket') . '.'
                        . str_replace('-internal.', '.', config('ali_oss.endpoint')) . '/'
                        . $file->path . $params;
                }
            }
        }
        return redirect($url);
    }

    function file($id)
    {
        if ($id) {
            $file = \App\Models\System\File::find($id);
            if ($file) {
                $url = Storage::url($file->path);
            }
        }
        return redirect($url);
    }
}
